using System;
using System.Collections;
using System.IO;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.COI;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;
using PHSRAG.SharePointUtility;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// Summary description for DownloadForm.
    /// </summary>
    public partial class DownloadForm : BasePage
    {
        private ICachePolicy _cachePolicy;
        private ICachePolicy _pageCachePolicy;

        protected void Page_Load(object sender, EventArgs e)
        {
            int docId = 0;
            int coiId = 0;
            byte[] pdfBlob = null;

            try
            {
                if (Request.QueryString["FileUrl"] != null)
                {
                    string FileUrl = Request.QueryString["FileUrl"];
                    DocumentLibrary dl = new DocumentLibrary();
                    pdfBlob = dl.GetFileFromSharePoint(FileUrl);
                    string[] FileName = FileUrl.Split('/');
                    DownloadFile(FileName[FileName.Length - 1].ToString(), true, pdfBlob);
                }
                else
                {
                    string ReportName = Request.QueryString["Report"];
                    if (Request.QueryString["DocId"] != null)
                    {
                        docId = Convert.ToInt32(Request.QueryString["DocId"]);
                    }
                    if (Request.QueryString["CoiId"] != null)
                    {
                        coiId = Convert.ToInt32(Request.QueryString["CoiId"]);
                    }
                    int parentId = Convert.ToInt32(Request.QueryString["ParentId"]);
                    string supervisorName = "";
                    if (parentId != 0)
                    {
                        Person person = new Person(null);
                        person.Load(DataAccess.ConnectionString, parentId);
                        supervisorName = string.Format("{0}, {1}", person.LastName, person.FirstName);
                    }

                    Document report = null;

                    if (string.IsNullOrEmpty(ReportName))
                    {
                        //Original implementation 
                        Hashtable incomingData = (Hashtable)_pageCachePolicy.GetCachedObject(Keys.IncomingDataKey);
                        if (incomingData != null)
                        {
                            Document attachment = (Document)incomingData[Keys.DocumentKey];
                            DownloadFile(attachment.Name, false, attachment.Blob);
                            _pageCachePolicy.UnCache(Keys.IncomingDataKey);
                        }
                    }
                    else
                    {
                        bool filterByLatestReportingPeriod;
                        Boolean.TryParse(Request.QueryString["filterByLatestReportingPeriod"], out filterByLatestReportingPeriod);
                        COIUserSummary oCOIUserSummary;
                        ConflictOfInterest coi = new ConflictOfInterest(new NullCachePolicy());
                        switch (ReportName.ToLower())
                        {
                            case "viewreport":
                                //Display View Report
                                if (docId == 0)
                                {
                                    coi.Load(DataAccess.ConnectionString, coiId);
                                    report = coi.Report = ConflictOfInterest.GetReport(null, DataAccess.ConnectionString,
                                        Server.MapPath("../COI"), coiId);
                                    coi.Dirty = true;
                                    coi.Save(DataAccess.ConnectionString);
                                }
                                else
                                {
                                    report = new Document(null);
                                    report.Load(DataAccess.ConnectionString, docId);
                                }
                                break;
                            case "viewdisclosure":
                                //Display View Disclosure Report
                                coi.Load(DataAccess.ConnectionString, coiId);
                                report = coi.GetDisclosure(null, DataAccess.ConnectionString,
                                    Server.MapPath("../COI"));
                                break;
                            case "attachments":
                                report = new Document(null);
                                if (Settings.GetKeyValue("SaveToSharePoint", false))
                                {
                                    Protocol protocol = new Protocol(_cachePolicy);
                                    protocol = (Protocol)_cachePolicy.GetCachedObject(protocol.CacheKey());
                                    report.Load(DataAccess.ConnectionString, docId);
                                    report.FolderHierarchy = ProtocolDocument.CreateFolderHierarchy(protocol, report.Id, report.Name);
                                    report.IsSharePointDocument = true;
                                }
                                else
                                {
                                    report.Load(DataAccess.ConnectionString, docId);
                                }
                                break;
                            case "coidtreport":
                                oCOIUserSummary = (COIUserSummary)Session[COIUserSummary.CacheKey];
                                UIUtility.TransmitToClient(oCOIUserSummary.GetDataContainer(),
                                    supervisorName, filterByLatestReportingPeriod);
                                break;
                            case "coisumreport":
                                oCOIUserSummary = (COIUserSummary)Session[COIUserSummary.CacheKey];
                                report = COICollection.GetSummaryReport(null, DataAccess.ConnectionString, Server.MapPath("../COI"),
                                    oCOIUserSummary.GetDataContainer(),
                                    supervisorName, filterByLatestReportingPeriod);
                                break;
                        }
                        if (report != null)
                        {
                            DownloadFile(report.Name, false, report.Blob);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        /// <summary>
        /// Writes the contents of the file to the response stream
        /// </summary>
        /// <param name="fname">Name of the file</param>
        /// <param name="forceDownload">Whether or not show the File Download dialogue</param>
        /// <param name="content">the contents of the file</param>
        private void DownloadFile(string fname, bool forceDownload, byte[] content)
        {
            string ext = Path.GetExtension(fname);
            string type;
            // set known types based on file extension  
            if (ext != null)
            {
                switch (ext.ToLower())
                {
                    case ".htm":
                    case ".html":
                        type = "text/HTML";
                        break;

                    case ".txt":
                        type = "text/plain";
                        break;

                    case ".doc":
                    case ".docx":
                    case ".docm":
                    case ".dot":
                    case ".dotx":
                    case ".dotm":
                    case ".rtf":
                        type = "Application/msword";
                        break;

                    case ".pdf":
                        type = "Application/pdf";
                        break;

                    case ".xls":
                    case ".xlsx":
                    case ".xlsm":
                    case ".xlt":
                    case ".xltx":
                    case ".xlsb":
                        type = "application/vnd.ms-excel";
                        break;

                    case ".ppt":
                    case ".pptx":
                    case ".pptm":
                    case ".pot":
                    case ".potx":
                    case ".potm":
                        type = "application/vnd.ms-powerpoint";
                        break;

                    default:
                        type = "application/octet-stream";
                        break;
                }
            }
            else
            {
                type = "Application/pdf";
            }

            Response.Clear();
            Response.ClearHeaders();

            Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fname + "\"");
            if (type != "")
            {
                Response.ContentType = type;
            }

            Response.AddHeader("Content-length", Convert.ToString(content.Length));
            Response.BinaryWrite(content);
            Response.Flush();

            //Response.Write("<script language=javascript>window.close();</script>");
            Response.End();
        }

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            _pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            _cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        #endregion
    }
}